function getSiteCfg() { 
    $.getJSON(
        "/api/tmpo/config_public/",
        function(json) {
            var val = 'POC: <a class="POCemail" href="mailto:' +
                      json.tmpo_poc_email + '">' + json.tmpo_poc_name +
                      '</a> Phone: (' + json.tmpo_poc_phone.substr(0,3) +
                      ') ' + json.tmpo_poc_phone.substr(3,3) + '-' + 
                      json.tmpo_poc_phone.substr(6,4);
            $("span.POCemail").append(val); 
        }
    );
}


var vehicle_history = '';
var vehicle_id = '';
var range_begin = '';
var range_end = '';
var month_days = '';
var current_month = '';
var vehicle_attrs = {};
var empty_cell = '<td align="center">&nbsp;</td>';
var drivers = [];

var setRowColors = function() {
    $("#vehicleLog tbody").removeClass('tableAlternateColor');
    $("#vehicleLog tbody:odd").addClass('tableAlternateColor');
};

var driverName = function(driver_id) {
    try {
        return drivers.filter(function (d) { 
            return d.id==driver_id;
        } )[0].name;
    } catch (e) {
        return "";
      }
};

var getDrivers = function() {
    $.getJSON('/api/tmpo/drivers/',
        function(response) {
            drivers = response['drivers'].sort();
        }
   );
};

var addHistory = function(row) {
    var date = row.dd1970_date.substr(0,10);
    var ops = row.operators.split(",").slice(0, -1);
    var cols = [
        '<td align="center">'+ $.y4m2d2_to_d2m3y4(date) +'</td>',
        '<td align="center" ><a href="/tmpo/vehicles/form1970/?id='+ 
        vehicle_id+'&date='+ date +
        '"><img title="Edit Motor Equipment Utilization Record" ' +
        'width="16" height="16" alt="Edit Motor Equipment '+
        'Utilization Record" src="/tmpo/images/icons/form_done.gif"/>'+
        '</a></td>',
        '<td align="center">'+ row.miles +'</td>',
        '<td align="center">' + row.fuel + ' gal</td>',
        '<td align="center">' + row.oil + ' qt</td>',
        '<td align="center">'+ ops.join(", ") + '</td>',
        '<td align="center">'+
        row.destination.split(",").slice(0, -1).join(", ") + '</td>'
    ];
    $("#vehicleLog").append('<tbody><tr>' + cols.join('') +
    '</tr></tbody>');
};

var addEmptyHistory = function(date) {
    var cols = [
        '<td align="center">'+ $.y4m2d2_to_d2m3y4(date) +'</td>',
        '<td align="center" ><a href="/tmpo/vehicles/form1970/?id=' + 
        vehicle_id + '&date=' + date +
        '"><img title="Add Motor Equipment Utilization Record" ' +
        'width="16" height="16" alt="Add Motor Equipment '+
        'Utilization Record" src="/tmpo/images/icons/form.gif"/>'+
        '</a></td>',
        empty_cell,
        empty_cell,
        empty_cell,
        empty_cell,
        empty_cell
    ];
    $('#vehicleLog').append('<tbody><tr>' + cols.join('') +
    '</tr></tbody>');
};

var addvehicle_history = function() {
    $('#vehicleLog tbody').remove();
    for (var i=1; i<=month_days; i+=1) {
        var mday = current_month+'-'+ ((i<10) ? '0'+i : i);
        var result = [];
        console.debug(vehicle_history.length)
        jQuery.map(vehicle_history, function(row){
            console.debug(row)
           if (row.dd1970_date.substr(0,10)==mday)
           {result = row;}
        });    
        
        if (result==="") {
            addEmptyHistory(mday);
        } else {
            addHistory(result);
        }
    }
};

var getHistory = function() {
    var url = '/api/tmpo/vehicles/' + vehicle_id + '/';
    $.getJSON(url,
        function(json) {
            vehicle_attrs = json.vehicles[0];
        }
    );

    url = '/api/tmpo/vehicles/history/';
    url += vehicle_id + '/' + range_begin + '/' + range_end + '/';
    $.getJSON(url,
        function(json) {
            vehicle_history = json.history;
            addvehicle_history();
            setRowColors();
        }
    );
};

function historyPrint() {
      $("#vehicleLog thead tr th:nth-child(2)").remove();
      $("#vehicleLog tbody tr td:nth-child(2)").remove();
      makePrinter("#vehicleLog")();
      resetTable();
}

function resetTable() {
//    Functional.install();
    $("#button_print").click( function() {historyPrint();}  );
    vehicle_id = $.qs('id');
    var url = ($.qs('date')=="current") ?
                    "/api/dates/month/" :
                    "/api/dates/month/"+$.qs('date');

    $.getJSON(url, 
        function(json){
            range_begin = json.info[0].current + '-01';
            range_end = json.info[0].next + '-01';
            month_days = json.info[0].number_of_days;
            current_month = json.info[0].current;
            getDrivers();
            getHistory();
            $("#vehicleLog caption").html(
                '<span class="captionDate"><a href="?id=' + vehicle_id +
                '&date=' +json.info[0].previous+
                '"><img src="/tmpo/images/icons/previous.gif" ' +
                'alt="Go to Previous Month" width="16" height="16" /></a> ' + 
                json.info[0].display + ' <a href="?id='+vehicle_id+'&date=' + 
                json.info[0].next + '"><img src="/tmpo/images/icons/next.gif" '+ 
                 'alt="Go to Next Month" width="16" height="16" /></a></span> '+
                 'Vehicle History: '+ vehicle_attrs.tagno);
        }
    );
}


function setProtoHTML() {    
    var proto_pre = {
        'schedule':'protoDriverScheduleTableHTML',
        'driver':'protoDriverRowHTML',
        'no_driver':'protoNoDriverRowHTML',
        'legend':'protoLegendHTML'
    };
    proto_html = {};
    $.each(proto_pre, function(i, v) {
        proto_html[i] = $("#" + v).html();
        $("#" + v).remove();
    });
}


jQuery(function($) {
    getSiteCfg();
    setProtoHTML();
    getDrivers();
    $(":radio, :checkbox").css("border", "none");
    $("#logoutNavButton").click( function() {
        $.post("/api/logout/", {},
            function() {
                window.location.href = "/tmpo/";   
            }
        );
    });
    if ($.cookie("tmpoHome")) {
        $("img.headerLogo").parent().attr('href', $.cookie("tmpoHome"));
    }
});